// import request from "../../utils/request";
// var api = require("../../utils/api");
// request(url, params, "GET").then(res => {
// })
const app = getApp()
import {
  getToken,
  getLocalData
} from './util.js'


function request(url, params, methods) {
  wx.showLoading({
    title: '正在加载',
  })
  var toQueryString = function(obj) {
    return obj ? '&' + Object.keys(obj).sort().map(function(key) {
      var val = obj[key];
      if (Array.isArray(val)) {
        return val.sort().map(function(val2) {
          return encodeURIComponent(key) + '[]=' + encodeURIComponent(val2);
        }).join('&');
      }
      return encodeURIComponent(key) + '=' + encodeURIComponent(val);
    }).join('&') : '';
  }
  let promise = new Promise(function(resolve, reject) {
    let relUrl = ''
    relUrl = url
    console.log(relUrl)
    //计算token
    params.access_token = getToken()
    params.openid = getLocalData().openid
    wx.request({
      url: relUrl,
      method: methods,
      data: params,
      success: function(res) {
        console.log(res)
        wx.hideLoading()
        if (res.data.code !== 0 && res.data.code != 1020011) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
          return
        }
        resolve(res.data);
      },
      fail: function(res) {
        wx.hideLoading()
        wx.showToast({
          title: res.data.msg,
          icon: 'none'
        })
        reject(res.data.msg)
        console.log(res)
      }
    });
  });
  return promise;
}
module.exports = request